﻿using System;
using System.IO;
using Tesla.Content;

namespace TeslaSamples {
    /// <summary>
    /// Extended FileResourceLocator that has a secondary directory for platform-specific
    /// content, such as shaders
    /// </summary>
    public class MultiFileResourceLocator : IResourceLocator {
        private String _rootDirectory;
        private String _secondaryDirectory;

        public String RootDirectory {
            get {
                return _rootDirectory;
            }
        }

        public String SecondaryDirectory {
            get {
                return _secondaryDirectory;
            }
        }

        public MultiFileResourceLocator(String rootDir, String secondaryDir) {
            _rootDirectory = rootDir;
            _secondaryDirectory = secondaryDir;
        }

        public String GetFullPath(String assetName) {
            return Path.Combine(_rootDirectory, Path.GetFullPath(assetName));
        }

        public IResource LocateResource(String assetName) {
            if(String.IsNullOrEmpty(assetName)) {
                throw new NullReferenceException("File name string cannot be null");
            }
            if(Path.IsPathRooted(assetName)) {
                if(File.Exists(assetName)) {
                    return new FileResource(assetName);
                }
            }

            String path = Path.Combine(_rootDirectory, assetName);
            if(File.Exists(path)) {
                return new FileResource(path);
            }

            path = Path.Combine(_secondaryDirectory, assetName);
            if(File.Exists(path)) {
                return new FileResource(path);
            }
            return null;
        }

        public string GetFullPathRelativeTo(string assetName, IResource relativeResource) {
            if(!(relativeResource is FileResource) || !File.Exists(relativeResource.FullName)) {
                return String.Empty;
            }

            return Path.Combine(Path.GetDirectoryName(relativeResource.FullName), assetName);
        }
    }
}
